package com.jpcc.vw.onlineRadio.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.SearchAlbumsAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.base.BaseActivity;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.SearchHistoryDbBean;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.CommonAlbumRadioSearchResultBean;
import com.jpcc.vw.onlineRadio.model.bean.LiveRadioDetailBean;
import com.jpcc.vw.onlineRadio.model.bean.NewSearchAlbumResultBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioSumBean;
import com.jpcc.vw.onlineRadio.model.bean.SimpleAlbumRadioEntity;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.SyncFavUtils;
import com.jpcc.vw.onlineRadio.utils.SyncSearchHistory;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.tracelog.TracelogInterface;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func2;

public class SearchResultActivity extends BaseActivity {

    @BindView(R.id.imv_top_search)
    ImageView imv_top_search;
    @BindView(R.id.swipe_refrsh_result)
    SmartRefreshLayout swipe_refrsh_result;
    @BindView(R.id.recyclerview_result)
    ListView recyclerview_result;
    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.tv_show_empty)
    TextView tv_show_empty;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;


    private IRadio radioModel;
    private DatabaseHelperOrm helper;
    private String searchKeyword;
    private SearchAlbumsAdapter adapter;
    private List<SimpleAlbumRadioEntity> datas = new ArrayList<>();

    private boolean is_refresh = true;
    private int page_index = 1;

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_result;
    }


    private void getLiveingProgramDetail(long radioId, String radioName) {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);

        Observable.zip(radioModel.GetPlayingProgramDetail(radioId), radioModel.getLiveSchedules(radioId, weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
            @Override
            public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                RadioSumBean response = new RadioSumBean();
                if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                    response.setLiveRadio(liveRadioDetailBean);
                    response.setRadioSchedule(radioDeailBean);
                    return response;
                }
                return response;
            }
        }).subscribe(new Subscriber<RadioSumBean>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(RadioSumBean radioSumBean) {
                List<Track> sources = new ArrayList<>();


                if (radioSumBean.getRadioSchedule() != null && radioSumBean.getRadioSchedule().getData() != null) {
                    for (RadioDeailBean.RadioSchedule schedule : radioSumBean.getRadioSchedule().getData()) {
                        if (!TextUtils.isEmpty(schedule.getListenBackUrl())) {
                            Track track = new Track();
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(radioName);
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setId(schedule.getId());
                            track.setTrackTitle(schedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(schedule.getRelatedProgram().getBackPicUrl());
                            track.setPlayUrl32(schedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            track.setAnnouncer(announcer);
                            track.setLive(false);


                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (schedule.getEndTime().equals("00:00")) {
                                    schedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(schedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(schedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(schedule.getStartTime());
                            track.setEndString(schedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);


                            sources.add(track);
                        }
                    }
                }


                Track liveRadio = new Track();
                if (radioSumBean.getLiveRadio() != null) {
                    LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(radioId);
                    subordinatedAlbum.setAlbumTitle(radioName);
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    liveRadio.setId(response.getData().getId());
                    liveRadio.setTrackTitle(response.getData().getProgramName());
                    liveRadio.setCoverUrlLarge(response.getData().getBackPicUrl());
                    liveRadio.setPlayUrl32(response.getData().getRate24AacUrl());
                    liveRadio.setCanDownload(false);
                    liveRadio.setDownloadUrl("");
                    liveRadio.type = "radio";
                    liveRadio.setSubordinatedAlbum(subordinatedAlbum);
                    liveRadio.setAnnouncer(announcer);
                    liveRadio.setLive(true);
                }
                Constants.LastModeFlag = false;
//                AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, liveRadio, true, 0);
                adapter.notifyDataSetChanged();

            }
        });
    }


    @Override
    public void setupView() {
        ButterKnife.bind(this);
        helper = DatabaseHelperOrm.getHelper(this);
        radioModel = new RadioImpl();
        imv_top_search.setVisibility(View.INVISIBLE);
        searchKeyword = getIntent().getStringExtra("key_search_word");
        layout_search.setVisibility(View.GONE);
        if (TextUtils.isEmpty(searchKeyword)) {
            this.finish();
        }


        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        adapter = new SearchAlbumsAdapter(datas, this);
        recyclerview_result.setAdapter(adapter);
        tv_title.setText(searchKeyword);
        swipe_refrsh_result.setEnableRefresh(false);
        swipe_refrsh_result.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                is_refresh = true;
                swipe_refrsh_result.setEnableLoadmore(true);
//                search();
                newSearch();
            }
        });

        swipe_refrsh_result.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                is_refresh = false;
//                search();
                newSearch();
            }
        });
        recyclerview_result.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("album".equals(datas.get(position).getType())) {
                    Intent intent = new Intent(SearchResultActivity.this, AlbumDetailActivity.class);
                    intent.putExtra("key_album_id", datas.get(position).getAlbumId());
                    intent.putExtra("key_is_radio", false);
                    intent.putExtra("key_from", 4);
                    intent.putExtra("key_search_result", true);
                    intent.putExtra("key_is_paied", false);
                    intent.putExtra("isvipFree",datas.get(position).isVipFree());
                    startActivity(intent);
                } else {
                    getLiveingProgramDetail(datas.get(position).getAlbumId(), datas.get(position).getTitle());
                }
            }
        });
        is_refresh = true;
//        search();
        newSearch();
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    public void onEvent(WaveAction action) {
        adapter.notifyDataSetChanged();
    }

    private void newSearch() {
        if (radioModel == null) {
            radioModel = new RadioImpl();
        }
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }
        radioModel.SearchAll(searchKeyword, 10, local_page).doOnSubscribe(new Action0() {
            @Override
            public void call() {
//                showProgress();
                if (is_refresh) {
                    progress_circular.setVisibility(View.VISIBLE);
                }
            }
        }).subscribe(new CommonSubscriber<CommonAlbumRadioSearchResultBean>() {
            @Override
            public void onSuccess(CommonAlbumRadioSearchResultBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                swipe_refrsh_result.finishRefresh();
                swipe_refrsh_result.finishLoadmore();
                if ((response.getAlbums() != null) && (response.getAlbums().size() == 0) && is_refresh) {
                    ToastUtils.show(getResources().getString(R.string.string_79));
                }
                if ((response.getAlbums() != null) && (response.getAlbums().size() > 0)) {
                    tv_show_empty.setVisibility(View.GONE);
                    if (is_refresh) {
                        refreshSearchHistory(searchKeyword);
                        datas.clear();
                        page_index = 1;
                    }
                    is_refresh = false;
                    page_index = page_index + 1;
                    datas.addAll(response.getAlbums());
                    adapter.setDatas(datas);
                    adapter.notifyDataSetChanged();
                } else {
                    swipe_refrsh_result.finishLoadmore();
                    swipe_refrsh_result.setEnableLoadmore(false);
                    if (is_refresh) {
                        tv_show_empty.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(BaseBean response) {
//                hideProgress();
                progress_circular.setVisibility(View.INVISIBLE);
                ToastUtils.show(response.getStatusMessage());
                if (is_refresh) {
                    tv_show_empty.setVisibility(View.GONE);
                }
            }
        });
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void refreshSearchHistory(String searchWord) {
        try {
            SearchHistoryDbBean result = helper.getSearchHistoryDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("searchWord", searchWord).queryForFirst();
            if (result == null) {
                result = new SearchHistoryDbBean();
                result.setUserId(MusicApplication.GetUserId());
                result.setSearchWord(searchWord);
                result.setTimeStamp(new Date().getTime());
                helper.getSearchHistoryDao().create(result);
            } else {
                result.setTimeStamp(new Date().getTime());
                helper.getSearchHistoryDao().update(result);
            }


            SyncSearchHistory.syncFav(this, new SyncFavUtils.onSyncFav() {
                @Override
                public void onSyncFavSuccess() {
//                    ToastUtils.show("Search history sync successed");
                }

                @Override
                public void onsyncFavFail() {
//                    ToastUtils.show(R.string.string_118);
                }
            });


        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
